import math
import operator
from functools import reduce

from PIL import Image, ImageFilter
import time
from PIL import ImageGrab
import pytesseract
import argparse
import cv2
import os
import pyautogui as pg
from pynput.keyboard import Listener

config={
    "key":"<105>",#监听的按键
    "screenRange":[133,179,1788,1109] #截图的范围x1,y1,x2,y2
}

def getMousePos():
    print(pg.position())

def getFileName(name):
    return(f'C:\\Users\\DingMiaoBin\\Desktop\\资料\\数字图像处理技术\\{name}.png')  # Press Ctrl+F8 to toggle the breakpoint.
def make_screenshot(range,fileName):
    """截图

    :param x1: 开始截图的x1坐标
    :param y1: 开始截图的x1标
    :param x2: 开始截图的x2坐标
    :param y2: 结束截图的y2坐标
    :return: None
    """
    bbox = (range[0], range[1], range[2],range[3])
    im = ImageGrab.grab(bbox)
    im.save(fileName)  # 保存截图文件的路径
release=True

def compareTwoImage(image1,image2):
    h1 = image1.histogram()
    h2 = image2.histogram()
    rms = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1))
    return rms
def on_press(key):
    global release
    if release:
        # print(key)
        if str(key)==config["key"]:
            print("ok")
            make_screenshot(config["screenRange"],getFileName(int(time.time())))
    release = False
def on_release(key):
    global release
    release=True

if __name__ == '__main__':
    with Listener(on_press=on_press,on_release=on_release) as listener:
        listener.join()